<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
	<title>ANTLR Specification: Vocabularies</title> 
</head>
<body bgcolor="#FFFFFF" text="#000000">
<h2><a name="Token Vocabularies">Token Vocabularies</a></h2> 
<p>
	Every grammar specifies language structure with rules (substructures) and vocabulary symbols.&nbsp; These symbols are equated with integer &quot;token types&quot; for efficient comparison at run-time.&nbsp; The files that define this mapping from symbol to token type are fundamental to the execution of ANTLR and ANTLR-generated parsers. &nbsp; This document describes the files used and generated by ANTLR plus the options used to control the vocabularies.
</p>
<h3><a name="Introduction">Introduction</a></h3> 
<p>
	A parser grammar refers to tokens in its vocabulary by symbol that will correspond to Token objects, generated by the lexer or other token stream, at parse-time. &nbsp;&nbsp; The parser compares a unique integer token type assigned to each symbol against the token type stored in the token objects.&nbsp; If the parser is looking for token type 23, but finds that the first lookahead token's token type, <font face="Courier New">LT(1).getType()</font>, is not 23, then the parser throws <font face="Courier New">MismatchedTokenException</font>.
</p>
<p>
	A grammar may have an import vocabulary and always has an export vocabulary, which can be referenced by other grammars.&nbsp; Imported vocabularies are never modified and represent the &quot;initial condition&quot; of the vocabulary.&nbsp; Do not confuse importVocabular
</p>
<p>
	The following represent the most common questions:
</p>
<h4><a name="How does ANTLR decide which vocabulary symbol gets what token type?">How does ANTLR decide which vocabulary symbol gets what token type?</a></h4> 
<p>
	Each grammar has a token manager that manages a grammar's export vocabulary.&nbsp; The token manager can be preloaded with symbol / token type pairs by using the grammar importVocab option.&nbsp; The option forces ANTLR to look for a file with mappings that look like:
</p>
<pre>PLUS=44</pre> 
<p>
	Without the importVocab option, the grammar's token manager is empty (with one caveat you will see later).
</p>
<p>
	Any token referenced in your grammar that does not have a predefined token type is assigned a type in the order&nbsp; encountered.&nbsp; For example, in the following grammar, tokens A and B will be 4 and 5, respectively:
</p>
<pre>class P extends Parser;
a : A B ;</pre> 
<p>
	Vocabulary file names are of the form: <em>Name</em><font face="Courier New">TokenTypes.txt</font>.
</p>
<h4><a name="Why do token types start at 4?">Why do token types start at 4?</a></h4> 
<p>
	Because ANTLR needs some special token types during analysis.&nbsp; User-defined token types must begin after 3.
</p>
<h4><a name="What files associated with vocabulary does ANTLR generate?">What files associated with vocabulary does ANTLR generate?</a></h4> 
<p>
	ANTLR generates <em>V</em><font face="Courier New">TokenTypes.txt</font> and <em>V</em><font face="Courier New">TokenTypes.java</font> for vocabulary <em>V</em> where <em>V</em> is either the name of the grammar or specified in an exportVocab=<em>V</em> option. The text file is sort of a &quot;freezedried&quot; token manager and represents the persistent state needed by ANTLR to allow a grammar in a different file to see a grammar's vocabulary including string literals etc...&nbsp; The Java file is an interface containing the token type constant definitions.&nbsp; Generated parsers <font face="Courier New">implement</font> one of these interfaces to obtain the appropriate token type definitions.
</p>
<h4><a name="How does ANTLR synchronize the symbol-type mappings between grammars in the same file and in different files?">How does ANTLR synchronize the symbol-type mappings between grammars in the same file and in different files?</a></h4> 
<p>
	The export vocabulary for one grammar must become the import vocabulary for another or the two grammars must share a common import vocabulary.
</p>
<p>
	Imagine a parser P in p.g:
</p>
<pre>// yields PTokenTypes.txt
class P extends Parser;
// options {exportVocab=P;} ---&gt; default!
decl : &quot;int&quot; ID ;</pre> 
<p>
	and a lexer L in l.g
</p>
<pre>class L extends Lexer;
options {
  importVocab=P; // reads PTokenTypes.txt
}
ID : ('a'..'z')+ ;</pre> 
<p>
	ANTLR generates LTokenTypes.txt and LTokenTypes.java even though L is primed with values from P's vocabulary.
</p>
<p>
	Grammars in different files that must share the same token type space should use the importVocab option to preload the same vocabulary.
</p>
<p>
	If these grammars are in the same file, ANTLR behaves in exactly same way. &nbsp; However, you can get the two grammars to share the vocabulary (allowing them both to contribute to the same token space) by setting their export vocabularies to the same vocabulary name.&nbsp; For example, with P and L in one file, you can do the following:
</p>
<pre>// yields PTokenTypes.txt
class P extends Parser;
// options {exportVocab=P;} ---&gt; default!
decl : &quot;int&quot; ID ;</pre> <pre>class L extends Lexer;
options {
  exportVocab=P; // shares vocab P
}
ID : ('a'..'z')+ ;</pre> 
<p>
	If you leave off the vocab options from L, it will choose to share the first export vocabulary in the file; in this case, it will share P's vocabulary.
</p>
<pre>// yields PTokenTypes.txt
class P extends Parser;
decl : &quot;int&quot; ID ;</pre> <pre>// shares P's vocab
class L extends Lexer;
ID : ('a'..'z')+ ;</pre> 
<p>
	The token type mapping file looks like this
</p>
<pre>P    // exported token vocab name
LITERAL_int=&quot;int&quot;=4
ID=5</pre> <h3><a name="Grammar Inheritance and Vocabularies">Grammar Inheritance and Vocabularies</a></h3> 
<p>
	Grammars that extend supergrammars inherit rules, actions, and options but what vocabulary does the subgrammar use and what token vocabulary does it use?&nbsp; ANTLR sees the subgrammar as if you had cut and paste all of the nonoverridden rules of the supergrammar into the subgrammar like an include.&nbsp; Therefore, the set of tokens in the subgrammar is the union of the tokens defined in the supergrammar and in the supergrammar.&nbsp; All grammars export a vocabulary file and so the subgrammar will export and use a different vocabulary than the supergrammar.&nbsp; The subgrammar always imports the vocabulary of the supergrammar unless you override it with an importVocab option in the subgrammar.
</p>
<p>
	A grammar Q that extends P primes its vocabulary with P's vocabulary as if Q had specified option <font face="Courier New">importVocab=P</font>.&nbsp; For example, the following grammar has two token symbols.
</p>
<pre>class P extends Parser;
a : A Z ;</pre> 
<p>
	The subgrammar, Q, initially has the same vocabulary as the supergrammar, but may add additional symbols.
</p>
<pre>class Q extends P;
f : B ;</pre> 
<p>
	In this case, Q defines one more symbol, B, yielding a vocabulary for Q of {A,B,C}.
</p>
<p>
	The vocabulary of a subgrammar is always a superset of the supergrammar's vocabulary. &nbsp; Note that overriding rules does not affect the initial vocabulary.
</p>
<p>
	If your subgrammar requires new lexical structures, unused by the supergrammar, you probably need to have the subparser use a sublexer.&nbsp; Override the initial vocabulary with an importVocab option that specifies the vocabulary of the sublexer.&nbsp; For example, assume parser P uses PL as a lexer.&nbsp; Without an importVocab override, Q's vocabulary would use P's vocab and, consequently, PL's vocabulary.&nbsp; If you would like Q to use token types from another lexer, say QL, do the following:
</p>
<pre>class Q extends P;
options {
  importVocab=QL;
}
f : B ;</pre> 
<p>
	Q's vocab will now be the same or a superset of QL's vocabulary.
</p>
<h3><a name="Recognizer Generation Order">Recognizer Generation Order</a></h3> 
<p>
	If all of your grammars are in one file, you do not have to worry about which grammar file ANTLR should process first, however, you still need to worry about the order in which ANTLR sees the grammars within the file.&nbsp; If you try to import a vocabulary that will be exported by a grammar later in the file, ANTLR will complain that it cannot load the file.&nbsp; The following grammar file will cause antlr to fail:
</p>
<pre>class P extends Parser;
options {
importVocab=L;
}

a : &quot;int&quot; ID;

class L extends Lexer;
ID : 'a';</pre> 
<p>
	ANTLR will complain that it cannot find LTokenTypes.txt because it has not seen grammar L yet in the grammar file.&nbsp; On the other hand, if you happened to have LTokenTypes.txt lying around (from a previous run of ANTLR on the grammar file when P did not exist?), ANTLR will load it for P and then overwrite it again for L.&nbsp; ANTLR must assume that you want to load a vocabulary generated from another file as it cannot know what grammars are approaching even in the same file.
</p>
<p>
	In general, if you want grammar B to use token types from grammar A (regardless of grammar type), then you must run ANTLR on grammar A first.&nbsp; So, for example, a tree grammar that uses the vocabulary of the parser grammar should be run after ANTLR has generated the parser.
</p>
<p>
	When you want a parser and lexer, for example, to share the same vocabulary space, all you have to do is place them in the same file with their export vocabs pointing at the same place.&nbsp; If they are in separate files, have the parser's import vocab set to the lexer's export vocab unless the parser is contributing lots of literals.&nbsp; In this case, reverse the import/export relationship so the lexer uses the export vocabulary of the parser.
</p>
<h3><a name="Tricky Vocabulary Stuff">Tricky Vocabulary Stuff</a></h3> 
<p>
	What if your grammars are in separate files and you still want them to share all or part of a token space.&nbsp; There are two solutions: (1) have the grammars import the same vocabulary or (2) have the grammars all inherit from the same base grammar that contains the common token space.
</p>
<p>
	The first solution applies when you have two lexers and two parsers that must parse radically different portions of the input.&nbsp; The example in examples/java/multiLexer of the ANTLR 2.6.0 distribution is such a situation.&nbsp; The javadoc comments are parsed with a different lexer/parser than the regular Java portion of the input.&nbsp; The &quot;*/&quot; terminating comment lexical structure is necessarily recognized by the javadoc lexer, but it is natural to have the Java parser enclose the launch of the javadoc parser with open/close token references:
</p>
<pre>javadoc
  : JAVADOC_OPEN
    {
    <small>DemoJavaDocParser jdocparser =
      new DemoJavaDocParser(getInputState());</small>
    jdocparser.content();
    }
    JAVADOC_CLOSE
  ;</pre> 
<p>
	The problem is: the javadoc lexer defines JAVADOC_CLOSE and hence defines its token type.&nbsp; The vocabulary of the Java parser is based upon the Java lexer not the javadoc lexer, unfortunately.&nbsp; To get the javadoc lexer and Java lexer to both see JAVADOC_CLOSE (and have the same token type), have both lexers import a vocabulary file that contains this token type definition.&nbsp; Here are the heads of DemoJavaLexer and DemoJavaDocLexer:
</p>
<pre>class DemoJavaLexer extends Lexer;
options {
  importVocab = Common;
}
...</pre> <pre>class DemoJavaDocLexer extends Lexer;
options {
  importVocab = Common;
}
...</pre> 
<p>
	CommonTokenTypes.txt contains:
</p>
<pre>Common // name of the vocab
JAVADOC_CLOSE=4</pre> 
<p>
	The second solution to vocabulary sharing applies when you have say one parser and three different lexers (e.g., for various flavors of C).&nbsp; If you only want one parser for space efficiency, then the parser must see the vocabulary of all three lexers and prune out the unwanted structures grammatically (with semantic predicates probably). &nbsp; Given CLexer, GCCLexer, and MSCLexer, make CLexer the supergrammar and have CLexer define the union of all tokens.&nbsp; For example, if MSCLexer needs &quot;_int32&quot; then reserve a token type visible to all lexers in CLexer:
</p>
<pre>tokens {
  INT32;
}</pre> 
<p>
	In the MSCLexer then, you can actually attach a literal to it.
</p>
<pre>tokens {
  INT32=&quot;_int32&quot;
}</pre> 
<p>
	In this manner, the lexers will all share the same token space allowing you to have a single parser recognize input for multiple C variants.
</p>
<pre><font face="Arial" size="1">Version: $Id: //depot/code/org.antlr/release/antlr-2.7.7/doc/vocab.html#2 $</font></pre> 
</body>
</html>
